package org.example.cglib;

import net.sf.cglib.proxy.Enhancer;

import java.lang.reflect.Field;
import java.util.Properties;

public class CglibProxyTest {
    public static void main(String[] args) {
        // 保存生成的代理类
        try {
            saveGeneratedCGlibProxyFiles("d:\\cglib\\");
        } catch (Exception e) {
            e.printStackTrace();
        }


        Enhancer enhancer = new Enhancer();

        // 将enhancer对象的 父类设置为Coder类
        enhancer.setSuperclass(Coder.class);
        enhancer.setUseFactory(false);

        // 将enhancer对象的方法拦截器设置为自定义的AttendanceMethodInterceptor：
        enhancer.setCallback(new AttendanceMethodInterceptor());

        // 调用enhancer对象的create()方法来生成一个代理对象
        Object object = enhancer.create();

        Coder coder = (Coder) object;
        coder.work();
    }

    /**
     * 保存生成的代理类
     *
     * @param dir
     * @throws Exception
     */
    public static void saveGeneratedCGlibProxyFiles(String dir) throws Exception {
        Field field = System.class.getDeclaredField("props");
        field.setAccessible(true);
        Properties props = (Properties) field.get(null);
        System.setProperty("cglib.debugLocation", dir);//dir为保存文件路径
        props.put("net.sf.cglib.core.DebuggingClassWriter.traceEnabled", "true");
    }
}
